package com.bangmai.util;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.net.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64Encoder;

public class AESMessageSigner {
	/**
	 * 发往海关的报文加密
	 */
	private static String keyWord = "MYgGnQE2+DAS973vd1DFHg==";
	private static String DEFAULT_CHARSET = "UTF-8";

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	public  static String encrypt(String content) {
		try {

			SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(keyWord),
					"AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");// 创建密码�?
			byte[] byteContent = content.getBytes(DEFAULT_CHARSET);
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始�?
			byte[] result = cipher.doFinal(byteContent);
			byte[] encode = Base64.encodeBase64(result);
			return new String(encode, DEFAULT_CHARSET); // 加密
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new RuntimeException("encrypt error.", e);
		}
	}

	public static String decrypt(String content) {
		if (content==null&&("").equals(content)) {
			return "该文件内容是空";
		}else {
			try {
				SecretKey key = new SecretKeySpec(Base64.decodeBase64(keyWord),"AES");
				Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");// 创建密码�?
				cipher.init(Cipher.DECRYPT_MODE, key);// 初始�?
				byte[] result = cipher.doFinal(Base64.decodeBase64(content));
				return new String(result, DEFAULT_CHARSET); // 解密
			} catch (Exception e) {
				throw new RuntimeException("decrypt error.", e);
			}
			
		}
		
	}

	public static String encrypt(byte[] content) {
		try {
			SecretKey key = new SecretKeySpec(Base64.decodeBase64(keyWord),"AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");// 创建密码�?
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始�?
			byte[] result = cipher.doFinal(content);
			byte[] encode = Base64.encodeBase64(result);
			return new String(encode, DEFAULT_CHARSET); // 加密
		} catch (Exception e) {
			throw new RuntimeException("encrypt error.", e);
		}
	}

	public String getKeyWord() {
		return keyWord;
	}

	public void setKeyWord(String keyWord) {
		this.keyWord = keyWord;
	}
	

}
